<?php

namespace App\Http\Controllers\Site\Custom\Purchaser;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Business\LicensedGood;
use App\B2BProject\Area;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyGoodsController extends Controller
{
    use HelperControllerBuildTrait;

    public function getIndex(Request $request)
    {
        // 分页处理
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        if ($request->ajax()) {
            // 获取授权表数据集合
            $authorizations = \Auth::user()->purchaserAuthorizationRequests()->available()->lists('id');

            $licensedGoods = LicensedGood::whereIn('authorization_id',
                $authorizations)->available();

            if ($name = $request->query('name')) {
                $licensedGoods->whereHas('goods', function (Builder $builder) use ($name) {
                    $builder->where('name', 'like', "%$name%");
                })->orWhereHas('authorizationRequest.provider.information', function (Builder $builder) use ($name) {
                    $builder->where('company', 'like', "%$name%");
                });
            }

            $licensedGoods
                = $licensedGoods->with('goods')->with('authorizationRequest')->with('priceStrategy')->paginate($request->query('pageSize'));

            $data = [];

            foreach ($licensedGoods as $item) {
                $data[] = [
                    'id'             => $item->id,
                    'src'            => $item->goods->cover(),
                    'shopname'       => $item->goods->name,
                    'price'          => sprintf("%.2f",
                        $item->goods->original_price * $item->goods->getPriceStrategy()),
                    'supplyName'     => $item->authorizationRequest->provider->information->company,
                    'scopeAuthority' => Area::getName($item->province_id) . ' ' . Area::getName($item->city_id),
                    'shopsituation'  => ['stock' => $item->goods->stock, 'sold' => 0, 'criticism' => 0],
                    'href'           => route('goods.detail', $item->goods->id),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $licensedGoods->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $licensedGoods->total(),
                ],
            ]);
        }

        return view('host/custom/purchaser/my-goods/index');
    }
}
